//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "PaymentTypeDlg.h"
#include "FormUtilities.h"

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"

const int CODE_DESCRIPTION = 1;

//---------------------------------------------------------------------------

__fastcall TfrmPaymentTypeDlg::TfrmPaymentTypeDlg(TComponent* Owner, TPaymentTypeBridge* bridge, TPaymentType* paymentType)
        : TForm(Owner)
{
   TFormUtilities::LocateForm(( TForm*)Owner, this);

   this->bridge      = bridge;
   this->paymentType = paymentType;

   if ( paymentType == NULL)
   {
      Caption = "Add new payment type";
   }
   else
   {
      Caption = "Update payment type";
      ShowPaymentType();
   }//if-else
}

void TfrmPaymentTypeDlg :: ShowPaymentType()
{
   edtDescription->Text = paymentType->description;
}

void TfrmPaymentTypeDlg :: GatherPaymentType()
{
   paymentType->description = edtDescription->Text;
}

void TfrmPaymentTypeDlg :: AddNewPaymentType()
{
   paymentType = new TPaymentType();

   try
   {
      GatherPaymentType();
      bridge->Add( paymentType);
   }
   __finally
   {
      delete paymentType;
      paymentType = NULL;
   }//try-finally
}

void TfrmPaymentTypeDlg :: UpdatePaymentType()
{
   GatherPaymentType();
   bridge->Update( paymentType->id, paymentType->description);
}

void TfrmPaymentTypeDlg :: ValidateData()
{
   if ( edtDescription->Text.Length() == 0)
      throw new TError( CODE_DESCRIPTION, "Payment type name must be entered");

   if ( edtDescription->Text.Length() > 255)
      throw new TError( CODE_DESCRIPTION, "Payment type description too long");
}

void TfrmPaymentTypeDlg :: HandleError( TError * e)
{
   MessageDlg( e->Message,
               mtError,
               TMsgDlgButtons() << mbOK,
               0);

   switch ( e->GetCode())
   {
      case CODE_DESCRIPTION :
         edtDescription->SetFocus();
         break;
   }//switch

   ModalResult = mrNone;
}

void __fastcall TfrmPaymentTypeDlg::btnOKClick(TObject *Sender)
{
   try
   {
      ValidateData();

      if ( paymentType == NULL)
         AddNewPaymentType();
      else
         UpdatePaymentType();
   }
   catch( TError * e)
   {
      HandleError( e);
   }//try-catch
}

